#!/bin/bash
# USAGE:
#	dem operation parameters
#	dem make [SRTM1/SRTM3] [extraBufferPercentage] [name]
#	dem load path/to/demfile.dem
#	dem unload
#	dem check
#       dem import path/to/demfile.dem "gdalOptions"
#	dem extent 
#       dem expand path/to/big.dem [merged.bil]
#	dem view
#
# DESCRIPTION:
#  DEM is an internal ADORE command.  
#  It can generate and load DEM settings to the environment.   
#
# INPUT:
#  dem: 
#	defaults to "dem check"
#  dem make SRTM1/SRTM3 extraBufferPercentage name
#	Calculates the master scene coverage and issues a call to construct_dem.sh 
#	Area if padded (enlarged) in all directions with the extraBufferPercentage.
#	You can call this function with no/some arguments. Defaults are: SRTM3 20 dem
#
#  dem load path/to/demfile.fmt
# 	Load's the specified dem file. 
#	Currently supported DEM formats:
#	  -output of "dem make"
#	  -construct_dem.sh (from TU-DELFT). The DEM file pattern is final_*.dem.
#	  -ArcGIS .flt files (with .hdr files)
#	  -ESRI .bil files (with .hdr files)
#	  -GMT .grd files. (Creates .dem and input_doris files in the current directory.)
#
#  dem unload
# 	Clears sam_in_dem, dac_in_dem and crd_in_dem. If you want to re-run dem make 
#       this can be used.
#
#  dem check:
#	Checks the environment DEM settings and suggests fixes to problems.
#
#  dem convert path/to/demfile.dem [gdalOptions]:
#       Convert given DEM file using GDAL to ESRI BIL format (GDAL EHDR format). Converted DEM then can be
#       loaded using dem load.
#  
#  dem extent:
#	Calculates and displays the corner coordinates of the DEM based on input values.
#
#  dem expand path/to/big.dem [merged.bil]
#       Merge a small dem with a big dem. The small dem overwrites the big one. 
#
#  dem view:
#	Display DEM using cpxview and the input values. Additional options can be passed. See 
#       "? view"
#
# OUTPUT:
#   dem make: Generates a folder with the dem. Leaves the hgt files in the current folder.
#   dem load: No outputs if success. Updates DORIS settings starting with sam_,dac_, and crd_.
#   dem unload: Displays a text message indicating cleared variables.
#   dem check: Checks and displays possible problems fixes on stdout.
#
# EXAMPLE:
#   dem convert merapi_15m.asc "-s_srs '+proj=utm +zone=49M +ellps=WGS84 +datum=WGS84 +units=m +no_defs' "
#   dem load merapi_15m.bil

#Parts of the code below is taken from construct_dem.sh, part of DORIS package.
## Made by Freek van Leijen and Zbigniew Perski
## Delft Institute of Earth Observation and Space Systems
## Delft University of Technology

function convertGdalDem(){
  local gdalFile demFile settingsFile demPath gdalOptions
  gdalFile="${1}"
  gdalOptions="${2}"
  gdalBasename=`basename ${gdalFile}`
  demFile=${gdalBasename%.*}.bil
  demPath=`pwd`
  #warp DEM to WGS84 latlon
  cmd=`echo gdalwarp ${gdalOptions} -t_srs \"+proj=latlong +datum=WGS84 +no_defs\" -ot Float32 -of EHDR \"${gdalFile}\" \"${demFile}\"`
  #         gdalwarp ${gdalOptions} -t_srs "+proj=latlong +datum=WGS84 +no_defs" -ot Float32 -of EHDR "${gdalFile}" "${demFile}"    
  eval "${cmd}"
}

function updateGrdDemSettings(){
  local grdFile demFile settingsFile demPath grdBaseName
  grdFile=${1}
  grdBaseName=`basename ${grdFile}`
  demFile=final_${grdBaseName%.grd}.dem
  settingsFile=input.doris_${grdBaseName%.grd}
  demPath=`pwd`
  #reads dem settings from grd file and modifies ADORE environment
  echo "Converting grd file to Doris Input format..."
  grd2xyz ${grdFile} -Zf > ${demFile}
  echo "Creating input file..."
  xmin=`grdinfo ${grdFile} | grep x_min | sed 's/.*x_min: //g' | sed 's/x_max.*//g'`
  ymax=`grdinfo ${grdFile} | grep y_max | sed 's/.*y_max: //g' | sed 's/y_inc.*//g'`
  xinc=`grdinfo ${grdFile} | grep x_inc | sed 's/.*x_inc: //g' | sed 's/name.*//g'| sed 's/units.*//g'`
  yinc=`grdinfo ${grdFile} | grep y_inc | sed 's/.*y_inc: //g' | sed 's/name.*//g'| sed 's/units.*//g'`
  Nx=`grdinfo ${grdFile} | grep nx | sed 's/.*nx: //g'`
  Ny=`grdinfo ${grdFile} | grep ny | sed 's/.*ny: //g'`
  
  echo -e "# The processing cards generated by $(basename $0) script." > $settingsFile
  echo -e "# Using parameters: $@" >> $settingsFile
  echo -e '# Copy the section(s) that is/are necessary to your processing setup.\n' >> $settingsFile
  echo "c         ___             ___" >> $settingsFile
  echo "comment   ___SIM AMPLITUDE___" >> $settingsFile
  echo "c                            " >> $settingsFile
  echo "SAM_IN_DEM     $demPath/$demFile" >> $settingsFile 
  echo -e "SAM_IN_FORMAT   r4 \t\t\t // default is short integer"  >> $settingsFile
  echo "SAM_IN_SIZE    $Ny $Nx" >> $settingsFile
  echo "SAM_IN_DELTA   $yinc $xinc" >> $settingsFile
  echo "SAM_IN_UL      $ymax $xmin"  >> $settingsFile
  echo "SAM_IN_NODATA  -32768" >> $settingsFile
  echo -e "SAM_OUT_FILE   master.sam \t // master simulated amplitude" >> $settingsFile
  echo -e "# SAM_OUT_DEM_LP   master_demhei_lp.raw \t // radarcoded dem to master extend" >> $settingsFile
  echo -e "# SAM_OUT_THETA_LP  master_theta_lp.raw \t // radarcoded dem to master extend" >> $settingsFile
  echo " " >> $settingsFile
  echo " " >> $settingsFile
  echo "c         ___          ___" >> $settingsFile
  echo "comment   ___DEM ASSIST___" >> $settingsFile
  echo "c                            " >> $settingsFile
  echo "DAC_IN_DEM     $demPath/$demFile" >> $settingsFile
  echo -e "DAC_IN_FORMAT   r4 \t\t\t // default is short integer"  >> $settingsFile   
  echo "DAC_IN_SIZE    $Ny $Nx" >> $settingsFile   
  echo "DAC_IN_DELTA   $yinc $xinc" >> $settingsFile
  echo "DAC_IN_UL      $ymax $xmin"  >> $settingsFile  
  echo "DAC_IN_NODATA  -32768" >> $settingsFile
  echo " " >> $settingsFile
  echo " " >> $settingsFile
  echo "c         ___             ___" >> $settingsFile
  echo "comment   ___REFERENCE DEM___" >> $settingsFile
  echo "c                            " >> $settingsFile
  echo "## CRD_METHOD   DEMINTRPMETHOD" >> $settingsFile
  echo "CRD_IN_DEM     $demPath/$demFile" >> $settingsFile
  echo -e "CRD_IN_FORMAT   r4 \t\t\t // default is short integer"  >> $settingsFile
  echo "CRD_IN_SIZE    $Ny $Nx" >> $settingsFile
  echo "CRD_IN_DELTA   $yinc $xinc" >> $settingsFile
  echo "CRD_IN_UL      $ymax $xmin"  >> $settingsFile
  echo "CRD_IN_NODATA  -32768" >> $settingsFile
  echo -e "CRD_OUT_FILE   master_slave.crd \t // reference dem phase" >> $settingsFile

  updateSrtmDemsettings ${demPath}/${settingsFile} ${demPath}/${demFile}
  
}

function copySettingsFromSamToDacAndCrd(){
  dac_in_dem=${sam_in_dem}
  dac_in_format=${sam_in_format}
  dac_in_size=${sam_in_size}
  dac_in_delta=${sam_in_delta}
  dac_in_ul=${sam_in_ul}
  dac_in_nodata=${sam_in_nodata}
  
  crd_in_dem=${sam_in_dem}
  crd_in_format=${sam_in_format}
  crd_in_size=${sam_in_size}
  crd_in_delta=${sam_in_delta}
  crd_in_ul=${sam_in_ul}
  crd_in_nodata=${sam_in_nodata}
}

function updateSrtmDemsettings(){
 #reads dem settings from settings file and modifies ADORE environment
  local settings_file dem_file
  
  settings_file=${1}
  dem_file=${2}
  [ ! -e ${settings_file} ] && echo "Settings file does not exist: ${settings_file}" && return;
  echo "Loading settings for sam_, dac_, and crd_"
  #sam_in_dem=`readDrs.sh ${settings_file} SAM_IN_DEM | tr -d '\n'`
  sam_in_dem=`canonicalPath ${dem_file}`
  sam_in_format=`readDrs.sh ${settings_file} SAM_IN_FORMAT | tr -d '\n'`
  sam_in_size=`readDrs.sh ${settings_file} SAM_IN_SIZE | tr -d '\n'`
  sam_in_delta=`readDrs.sh ${settings_file} SAM_IN_DELTA | tr -d '\n'`
  sam_in_ul=`readDrs.sh ${settings_file} SAM_IN_UL | tr -d '\n'`
  sam_in_nodata=`readDrs.sh ${settings_file} SAM_IN_NODATA | tr -d '\n'`
  copySettingsFromSamToDacAndCrd
}


function makeSrtmDem(){
  local srtm buffer name center_lat center_lon size_rg size_az radar_band_width inc_angle
  local size_rg_km size_az_km dem_area settings_file
  srtm=${1:-SRTM3}  
  buffer=${2:-20}
  name=${3:-dem}
  echo "I'll generate ${srtm} DEM."
  echo "Extra buffer size is set to ${buffer}%."  
  #check resfiles
  if [ ! -e ${m_resfile} ]; then
    echo "I can not find the m_resfile. I'll try to run m_readfiles to create it."
    if [ ! -e ${m_in_dat} ]; then
      echo "Can not locate the master data file (m_in_dat). Please check your settings."
      return;
    else
      m_readfiles
    fi
  fi
  if [ "${slc_rg_res:-isEmpty}" == "isEmpty" ] || [ "${slc_az_res:-isEmpty}" == "isEmpty" ]; then
    if [ ! -e ${i_resfile} ]; then
      echo "I can not find the i_resfile. This is required to calculate pixel size."
      echo "Please specify azimuth and range resolution manually in the following variables: slc_az_res, slc_rg_res"
      echo "Or you can run the coarse_orbits step and re-run dem make."
      return;
    else
      radar_band_width=`readRes.sh ${m_resfile} readfiles Total_range_band_width | tr -d '\n'`
      echo "Radar Band Width=${radar_band_width}"
      inc_angle=`readRes.sh ${i_resfile} coarse_orbits inc_angle | tr -d '\n'`
      [ -z "${inc_angle}" ] && echo -e "Can not read incidence angle from ${i_resfile}. \n Using default:23.2" && inc_angle=23.2
      # get range resolution
      [ -z "${slc_rg_res}" ] && slc_rg_res=`echo "2.99e8 ${radar_band_width} ${inc_angle}" | awk '{PI=3.14159;printf "%d", $1/($2*1e6*cos($3/180*PI))};'`
      if [ -z "${slc_az_res}" ]; then
        [ "${m_in_method}" == "ASAR" -o  "${m_in_method}" == "ERS" ] && slc_az_res=`echo "${slc_rg_res}" | awk '{printf "%d", $1/5};'`
        [ "${m_in_method}" == "TSX" ] && slc_az_res=2.4 #Antenna L=4.8m theoretical stripmap res=L/2
      fi
    fi
  fi
  echo "SLC resolution [Azimuth x Range]: ${slc_az_res} x ${slc_rg_res}"
  ## get center coordinates
  center_lat=`readRes.sh ${m_resfile} readfiles Scene_centre_latitude  |awk '{printf "%f", $1};'`
  center_lon=`readRes.sh ${m_resfile} readfiles Scene_centre_longitude |awk '{printf "%f", $1};'`
  ## get crop size
  #last_step="readfiles" #`check ${s_resfile} | grep -w "1" | cut -f2 -d:`
  #first_line=`readRes.sh ${m_resfile} ${last_step} First_line | tr -d '\n'`
  #last_line=`readRes.sh ${m_resfile} ${last_step} Last_line  | tr -d '\n'`
  #first_pixel=`readRes.sh ${m_resfile} ${last_step} First_pixel | tr -d '\n'`
  #last_pixel=`readRes.sh ${m_resfile} ${last_step} Last_pixel | tr -d '\n'`
  size_rg=`readRes.sh ${m_resfile} readfiles Number_of_pixels_original | tr -d '\n'` #`echo "${last_pixel} ${first_pixel}" | awk '{printf "%d", $1-$2+1};'`
  size_az=`readRes.sh ${m_resfile} readfiles Number_of_lines_original | tr -d '\n'`#`echo "${last_line} ${first_line}" | awk '{printf "%d", $1-$2+1};'`
    
  ## find bounding box
  size_rg_km=`echo "${size_rg} ${slc_rg_res} ${buffer}" | awk '{printf "%d", ($1*$2/1000)*(100+$3)/100};'`
  size_az_km=`echo "${size_az} ${slc_az_res} ${buffer}" | awk '{printf "%d", ($1*$2/1000)*(100+$3)/100};'`
  echo "DEM size in km [Azimuth x Range]: ${size_az_km} x ${size_rg_km}"
  dem_area=`boundingBox.sh $center_lat $center_lon $size_rg_km $size_az_km | tr -d '\n'`  
  echo "Calculated bounding box for input: ${dem_area}"

  ## call construct_dem.sh
  echo "Creating DEM with: construct_dem.sh ${name} ${dem_area} ${srtm}"
  construct_dem.sh ${name} ${dem_area} ${srtm}
  ## modify settings
  settings_file="${name}/input.doris_${name}"  
  updateSrtmDemsettings "${settings_file}" "${name}/final_${name}.dem"
}


function updateArcGisDemSettings(){
 #reads dem settings from .hdr file and modifies ADORE environment
  local settings_file demFile nrows ncols lx lly uly
  settings_file=${1}
  demFile=${2}
  
  [ ! -e ${settings_file} ] && echo "Settings file does not exist: ${settings_file}" && return;
  echo "Loading settings for sam_, dac_, and crd_"
  sam_in_dem=${demFile}
  sam_in_format='r4'
  #set -x
  nrows=`grep -i -w "nrows" ${settings_file} | awk '{printf "%d", $2};'| tr -d '\n'`
  ncols=`grep -i -w "ncols" ${settings_file} | awk '{printf "%d", $2};'| tr -d '\n'`
  cellsize=`grep -i -w "cellsize" ${settings_file} | awk '{gsub(",",".");printf "%.8f", $2};'| tr -d '\n'` #change comma to dots if any
  lx=`grep -i -w "xllcorner" ${settings_file} | awk '{gsub(",",".");printf "%.8f", $2};'| tr -d '\n'` # get left x. 
  lly=`grep -i -w "yllcorner" ${settings_file} | awk '{gsub(",",".");printf "%.8f", $2};'| tr -d '\n'`  # get lower left y
  uly=`echo ${lly} ${nrows} ${cellsize} | awk '{printf "%.8f", $1+$2*$3};' |tr -d '\n'` #calculate upper left y
  sam_in_size="${nrows} ${ncols}"
  sam_in_delta="${cellsize} ${cellsize}"
  sam_in_ul="${uly} ${lx}"
  sam_in_nodata=`grep -i -w "NODATA_value" ${settings_file} | awk '{gsub(",",".");printf "%d", $2};'| tr -d '\n'`
  #set +x
  copySettingsFromSamToDacAndCrd
}

function updateEsriBilDemSettings(){
 #reads dem settings from .hdr file and modifies ADORE environment
  local settings_file demFile nrows ncols lx lly uly xdim ydim
  settings_file=${1}
  demFile=${2}
  
  [ ! -e ${settings_file} ] && echo "Settings file does not exist: ${settings_file}" && return;
  echo "Loading settings for sam_, dac_, and crd_"
  sam_in_dem=${demFile}
  sam_in_format='r4'
  #set -x
  nrows=`grep -i -w "nrows"  ${settings_file} | awk '{printf "%d", $2};'| tr -d '\n'`
  ncols=`grep -i -w "ncols"  ${settings_file} | awk '{printf "%d", $2};'| tr -d '\n'`
  xdim=`grep  -i -w "xdim"   ${settings_file} | awk '{printf "%f", $2};'| tr -d '\n'`
  ydim=`grep  -i -w "ydim"   ${settings_file} | awk '{printf "%f", $2};'| tr -d '\n'`
  ulx=`grep   -i -w "ulxmap" ${settings_file} | awk '{printf "%f", $2};'| tr -d '\n'` 
  uly=`grep   -i -w "ulymap" ${settings_file} | awk '{printf "%f", $2};'| tr -d '\n'` 
  sam_in_size="${nrows} ${ncols}"
  sam_in_delta="${ydim} ${xdim}"
  sam_in_ul="${uly} ${ulx}"
  sam_in_nodata=`grep -i -w "NODATA" ${settings_file} | awk '{printf "%f", $2};'| tr -d '\n'`
  [ -z "${sam_in_nodata}" ] && sam_in_nodata=-9999 # Set to default
  #set +x
  copySettingsFromSamToDacAndCrd
}

function demLoad(){
  if [ ${1:-undefined} == "undefined" ]; then
    echo "No DEM specified. Using sam_in_dem"
    demFile=${sam_in_dem};
  else
    demFile=${1};
  fi
  #read input settings 	
  if [ -e "${demFile}" ]; then
    if [[ "${demFile}" == *.dem* ]]; then
      echo "You are using this SRTM DEM: ${demFile}"
      #get input settings file.
      demPath=`dirname ${demFile}`
      demBasename=`basename ${demFile}`
      demBasename=${demBasename%%.dem*}	#chop the last .dem
      demBasename=${demBasename##*final_} #chop the initial final
      settings_file="input.doris_${demBasename}"        
      echo "I expect to find settings file at: ${demPath}/${settings_file}"
      if [ -e "${demPath}/${settings_file}" ]; then
        updateSrtmDemsettings ${demPath}/${settings_file} ${demFile}
      else 
        echo "I can not find the settings file. Can you check?"
      fi
    elif [[ "${demFile}" == *.flt* ]]; then
      echo "You are using an ArcGIS binary file as DEM: ${demFile}"        
      #get header file.
      demPath=`dirname ${demFile}`
      demBasename=`basename ${demFile}`
      demBasename=${demBasename%%.flt*}     #chop the last .flt
      settings_file="${demBasename}.hdr"
      echo "I expect to find the header file at: ${demPath}/${settings_file}"
      if [ -e "${demPath}/${settings_file}" ]; then
        updateArcGisDemSettings ${demPath}/${settings_file} ${demFile}
      else
        echo "I can not find the header file. Can you check?"
      fi
    elif [[ "${demFile}" == *.grd* ]]; then
      echo "You are using a GMT grid file as DEM: ${demFile}"
      updateGrdDemSettings `canonicalPath ${demFile}`
    elif [[ "${demFile}" == *.bil* ]]; then
      echo "You are using ESRI .hdr labelled *.BIL format as DEM."
      demPath=`dirname ${demFile}`
      demBasename=`basename ${demFile}`
      demBasename=${demBasename%%.bil*}     #chop the last .bil
      settings_file="${demBasename}.hdr"
      echo "I expect to find the header file at: ${demPath}/${settings_file}"
      if [ -e "${demPath}/${settings_file}" ]; then
        updateEsriBilDemSettings ${demPath}/${settings_file} ${demFile}
      else
        echo "I can not find the header file. Can you check?"
      fi
      
    
    else
      error "I can only read the following formats: *.dem, *.flt, *.grd, *.bil"
      echo "Please try converting the given data with gdal."
    fi        
  else
    echo "The DEM file does not exist: ${sam_in_dem}"  
  fi

}

function checkDem(){
  #check if dem exists and in sync with environment
  everythingOK=0; #0 Yes, others no
  [ ! -e "${sam_in_dem}" ] && everythingOK=1;
  [ ! -e "${dac_in_dem}" ] && everythingOK=2;
  [ ! -e "${crd_in_dem}" ] && everythingOK=3;
  if [ ${everythingOK} -ne 0 ]; then
    case ${everythingOK} in
    1)
      echo "Error: 1"
      echo "sam_in_dem does not exist: ${sam_in_dem}"
      echo "If you did not get errors 2 and 3 run \"settings check\" and fix."    
    ;;
    2)
      echo "Error: 2"
      echo "dac_in_dem does not exist: ${dac_in_dem}"
      echo "If you did not get errors 1 and 3 run \"settings check\" and fix."    
    ;;
    3)
      echo "Error: 3"
      echo "crd_in_dem does not exist: ${crd_in_dem}"
      echo "If you did not get errors 1 and 2 run \"settings check\" and fix."    
    ;;
    *)
      echo "Error: -"
      echo "There are some problems with your DEM settings."
      echo "But I don't know how to help you... Sorry..."
    ;;
    esac
  else
    echo "Everything seems fine." 
  fi
}

function demExtent(){
  local demRows demCols demTop demLeft deltaDown deltaRight
  local demBottom demRight
  demRows="${sam_in_size%% *}"
  demCols="${sam_in_size##* }"
  demTop="${sam_in_ul%% *}"
  demLeft="${sam_in_ul##* }"
  deltaDown="${sam_in_delta%% *}"
  deltaRight="${sam_in_delta##* }"
  demBottom=`echo ${demTop} ${demRows} ${deltaDown} | awk '{printf "%.6f", $1-$2*$3};' |tr -d '\n'` #calculate lat.min
  demRight=`echo ${demLeft} ${demCols} ${deltaRight} | awk '{printf "%.6f", $1+$2*$3};' |tr -d '\n'` #calculate lon.max
  echo "DEM extent w/e/s/n: ${demLeft}/${demRight}/${demBottom}/${demTop}"
}

function demUnload(){
  #unload all dem settings
  echo "Unloading settings for sam_in_dem, dac_in_dem, and crd_in_dem"
  sam_in_dem=""
  
  dac_in_dem=${sam_in_dem}
  
  crd_in_dem=${sam_in_dem}
  
}

function demView(){
  cpxview -w${sam_in_size##* } -f${sam_in_format} -qnormal ${@} ${sam_in_dem} 
}

function demExpand(){
#       dem expand path/to/big.dem [merged.bil]
  #check to see if gdal can read the dem files.
  #if it is a doris dem, create an hdr file.
  #then run gdal_merge  
  [ ! -f "${sam_in_dem}" ] && echo "Please load the dem to expand first." && return 
  local smallDem=${sam_in_dem} #already loaded
  local bigDem=${1}
  local mergedDem=${2:-merged.bil}
  
  gdalinfo ${smallDem} &> /dev/null
  [ $? -ne 0 ] && createHeader ${smallDem}
  gdalinfo ${bigDem} &> /dev/null
  [ $? -ne 0 ] && createHeader ${bigDem}
  gdal_merge.py -init 0 -o ${mergedDem} -of EHdr -ps ${sam_in_delta} ${bigDem} ${smallDem} 
}

function createHeader(){
  local demname=${1}
  local curDem=${sam_in_dem}  
  if [ "${curDem}" != "${demname}" ]; then
    demLoad ${demname}
  fi
  local fldr=`dirname ${1}`
  local hdrname=`basename ${1}`
  hdrname="${fldr}/${hdrname%%.*}.hdr"  
  echo "BYTEORDER      I" > ${hdrname}
  echo "LAYOUT         BIL" >>${hdrname}
  echo "NROWS          ${sam_in_size%% *}" >>${hdrname}
  echo "NCOLS          ${sam_in_size##* }" >>${hdrname}
  echo "NBANDS         1" >>${hdrname}
  echo "NBITS          32" >>${hdrname}
  echo "BANDROWBYTES   $(( ${sam_in_size%% *} * 4 ))" >>${hdrname}
  echo "TOTALROWBYTES  $(( ${sam_in_size%% *} * 4 ))" >>${hdrname}
  echo "PIXELTYPE      FLOAT" >>${hdrname}
  echo "ULXMAP         ${sam_in_ul##* }" >>${hdrname}
  echo "ULYMAP         ${sam_in_ul%% *}" >>${hdrname}
  echo "XDIM           ${sam_in_delta##* }" >>${hdrname}
  echo "YDIM           ${sam_in_delta%% *}" >>${hdrname}
  if [ "${curDem}" != "${demname}" ]; then
    demLoad ${curDem}
  fi
}

function createGiantRSC(){
  local demname="${crd_out_dem_lp}"
  local fldr=`dirname ${demname}`
  local hdrname=`basename ${demname}`
  hdrname="${fldr}/${hdrname%%.*}.rsc"  
  # the coordinate calculations are based on an euclidian geometry and might not be very accurate
  # see http://stackoverflow.com/questions/1624574/calculate-lat-lng-of-corners-of-ground-overlay-from-kml-file
  local kmlfile A north south east west x y 
  if [ -f "$i12sFolder/resample.kml" ]; then
    kmlfile="$i12sFolder/resample.kml"
  elif [ -f $resampleFolder/*_${master}/resample.kml ]; then
    kmlfile="$resampleFolder/*_${master}/resample.kml"
  else
    error "Can not find resample.kml file."
    return 
  fi
  A=`grep rotation ${kmlfile} |tr "<" ">"| cut -d">" -f3`
  north=`grep north ${kmlfile} |tr "<" ">"| cut -d">" -f3`
  south=`grep south ${kmlfile} |tr "<" ">"| cut -d">" -f3`
  east=`grep east ${kmlfile} |tr "<" ">"| cut -d">" -f3`
  west=`grep west ${kmlfile} |tr "<" ">"| cut -d">" -f3`
  cy=`echo ${north} ${south} | awk '{print ($1+$2)/2}'` # center lat
  cx=`echo ${east} ${west} | awk '{print ($1+$2)/2}'`   # center lon 
  x=`echo ${east} ${west} | awk '{print ($1-$2)/2}'`    # width lon
  y=`echo ${north} ${south} | awk '{print ($1-$2)/2}'`  # width lat
  A=`echo ${A} | awk '{print $1*3.14159265/180}'`
  nex=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $1 + $3*cos($5) - $4*sin($5)}'` # north east x lon
  ney=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $2 + $3*sin($5) + $4*cos($5)}'`
  nwx=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $1 - $3*cos($5) - $4*sin($5)}'`
  nwy=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $2 - $3*sin($5) + $4*cos($5)}'`
  sex=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $1 + $3*cos($5) + $4*sin($5)}'`
  sey=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $2 + $3*sin($5) - $4*cos($5)}'`
  swx=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $1 - $3*cos($5) + $4*sin($5)}'`
  swy=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $2 - $3*sin($5) - $4*cos($5)}'` # south west y lat
  # dem resolution
  local dem_az_res dem_rg_res
  dem_az_res=`echo ${slc_az_res} ${coh_multilook%% *} | awk '{print $1 * $2}'`
  dem_rg_res=`echo ${slc_rg_res} ${coh_multilook##* } | awk '{print $1 * $2}'`
  # create the rsc file
  echo "WIDTH               `readRes.sh ${i_resfile} "comp_refdem" "Number of pixels (multilooked)"`" >> ${hdrname}
  echo "FILE_LENGTH         `readRes.sh ${i_resfile} "comp_refdem" "Number of lines (multilooked)"`" >> ${hdrname}
  echo "LAT_REF1            ${nwy}" >> ${hdrname}
  echo "LON_REF1            ${nwx}" >> ${hdrname}
  echo "LAT_REF2            ${swy}" >> ${hdrname}
  echo "LON_REF2            ${swx}" >> ${hdrname}
  echo "LAT_REF3            ${sey}" >> ${hdrname}
  echo "LON_REF3            ${sex}" >> ${hdrname}
  echo "LAT_REF4            ${ney}" >> ${hdrname}
  echo "LON_REF4            ${nex}" >> ${hdrname}
  echo "AZIMUTH_PIXEL_SIZE  ${dem_az_res}" >> ${hdrname}
  echo "RANGE_PIXEL_SIZE    ${dem_rg_res}" >> ${hdrname}
}

function createRoipacRSC(){
  local demname="${1}"
  [ -z "${demname}" ] && demname="${sam_in_dem}"
  local curDem="${sam_in_dem}"
  if [ "${curDem}" != "${demname}" ]; then
    demLoad ${demname}
  fi
  local fldr=`dirname ${demname}`
  local hdrname=`basename ${demname}`
  hdrname="${fldr}/${hdrname%%.*}.rsc"  
  echo "WIDTH          ${sam_in_size%% *}" >> ${hdrname}
  echo "FILE LENGTH    ${sam_in_size##* }" >> ${hdrname}
  echo "XMIN           0" >> ${hdrname}
  echo "XMAX           $((${sam_in_size%% *}-1))" >> ${hdrname}
  echo "YMIN           0" >> ${hdrname}
  echo "YMAX           $((${sam_in_size##* }-1))" >> ${hdrname}
  echo "X_FIRST        ${sam_in_ul##* }" >> ${hdrname}
  echo "Y_FIRST        ${sam_in_ul%% *}" >> ${hdrname}
  echo "X_STEP         ${sam_in_delta##* }" >> ${hdrname}
  echo "Y_STEP         ${sam_in_delta%% *}" >> ${hdrname}
  echo "X_UNIT         degrees" >> ${hdrname}
  echo "Y_UNIT         degrees" >> ${hdrname}
  echo "Z_OFFSET       0" >> ${hdrname}
  echo "Z_SCALE        1" >> ${hdrname}
  echo "PROJECTION     LATLON" >> ${hdrname}
  if [ "${curDem}" != "${demname}" ]; then
    demLoad ${curDem}
  fi  
}

function demExport(){
  case ${1} in
    roipac)
      shift
      createRoipacRSC ${@}  
    ;;
    giant)
      shift
      createGiantRSC ${@}  
    ;;
    *)
      error "Currently dem export only supports: roipac, giant"
    ;;    
  esac    
}

function main(){
  local srtm buffer name demFile demPath demBasename settings_file
  case ${1} in
    make)
      srtm=${2:-SRTM3}
      buffer=${3:-20}
      name=${4:-dem}
      #check if dem exists. 
      #if not make new.
      if [ ! -e "${sam_in_dem}" ]; then
        makeSrtmDem ${srtm} ${buffer} ${name}
      else
        echo "It seems like you already have a DEM set for sam_in_dem: ${sam_in_dem}"
      fi
    ;;  
    load)
      shift
      demLoad "${@}"
    ;;
    convert)
      shift
      error "DEM CONVERT is deprecated."
      error "Please use DEM IMPORT instead."
      convertGdalDem "${@}"
    ;;
    import)
      shift
      convertGdalDem "${@}"
    ;;
    unload)
      demUnload
    ;;
    extent)
      demExtent
    ;;
    view)
      shift 
      demView "${@}"
    ;;
    expand)
      shift
      demExpand "${@}"      
    ;;
    export)
      shift
      demExport "${@}"      
    ;;
    *)
      #check to see if dem exists and it is loaded.
      checkDem
    ;;
  esac
   
}

#run main function
main "${@}"